<?php
/**
 * Created by PhpStorm.
 * User: zhongyb
 * Date: 16-8-30
 * Time: 下午6:20
 */
namespace common\repositories\common;

use common\entities\common\MyscrmOrganizationRemindDetailsEntity;
use common\repositories\BaseRepository;
use common\entities\common\MyscrmOrganizationRemindEntity;
use common\support\StringHelper;
use pahanini\curl\Multi;
use linslin\yii2\curl;
use Yii;
use yii\helpers\ArrayHelper;

class MyscrmOrganizationRemindRepository extends BaseRepository {

    public function addRemind($organizationId, $contractId, $isStop, $reason, $isXq)
    {
        $entity = new MyscrmOrganizationRemindEntity();
        $entity->isNewRecord = true;
        $entity->remindId = StringHelper::uuid();
        $entity->organizationId = $organizationId;
        $entity->contractId = $contractId;
        $entity->isStop = $isStop;
        $entity->reason = $reason;
        $entity->CreatedOn = date('Y-m-d H:i:s');
        $entity->ModifiedOn = date('Y-m-d H:i:s');
        $entity->userId = Yii::$app->user->identity->userguid;
        $entity->userName = Yii::$app->user->identity->username;
        $entity->isXq = $isXq;

        if($entity->save() === false){
            return false;
        }

        return $entity->remindId;
    }

    public function addRemindDetails($organizationId, $contractId, $projectId, $appCode, $isXq)
    {
        $entity = new MyscrmOrganizationRemindDetailsEntity();
        $entity->isNewRecord = true;
        $entity->detailsId = StringHelper::uuid();
        $entity->organizationId = $organizationId;
        $entity->contractId = $contractId;
        $entity->projectId = $projectId;
        $entity->appCode = $appCode;
        $entity->CreatedOn = date('Y-m-d H:i:s');
        $entity->CreatedBy = Yii::$app->user->identity->userguid;
        $entity->isXq = $isXq;

        if($entity->save() === false){
            return false;
        }

        return true;
    }


    public function updateRemind($remindId, $isStop, $reason, $isXq)
    {
        /** @var MyscrmOrganizationRemindEntity $entity */
        $entity = MyscrmOrganizationRemindEntity::find()
            ->where(['remindId' => $remindId])
            ->one();

        if($entity){
            $entity->reason = $reason;
            $entity->isStop = $isStop;
            $entity->isXq = $isXq;
            $entity->ModifiedOn = date('Y-m-d H:i:s');
            $entity->ModifiedBy = Yii::$app->user->identity->userguid;
            $entity->userName = Yii::$app->user->identity->username;

            if($entity->save() !== false){
                return true;
            }
        }

        return false;
    }

    public function getAllRemind()
    {
        return MyscrmOrganizationRemindEntity::find()
            ->asArray()
            ->all();
    }

    public function getRemind($contractId)
    {
        return MyscrmOrganizationRemindEntity::find()
            ->where(['contractId' => $contractId])
            ->asArray()
            ->one();
    }

    public function getRemindByRemindId($remindId)
    {
        return MyscrmOrganizationRemindEntity::find()
            ->where(['remindId' => $remindId])
            ->asArray()
            ->one();
    }

    public function getRemindDetailsByProjectApp($projectId, $appCode)
    {
        return MyscrmOrganizationRemindDetailsEntity::find()
            ->where(['projectId' => $projectId])
            ->andWhere(['appCode' => $appCode])
            ->orderBy('CreatedOn desc')
            ->asArray()
            ->one();
    }

    public function getRemindDetails($contractId, $projectId = '')
    {
        return MyscrmOrganizationRemindDetailsEntity::find()
            ->filterWhere(['contractId' => $contractId])
            ->andFilterWhere(['projectId' => $projectId])
            ->asArray()
            ->all();
    }

    public function getRemindDetailsByRemindId($remindId)
    {
        return MyscrmOrganizationRemindDetailsEntity::find()
            ->where(['remindId' => $remindId])
            ->asArray()
            ->all();
    }

    public static function checkProjectAppStatus($orgCode, $details)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-disable-status-and-newest-contract',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'details' => $details,
        ];

        $url = $siteUrl . '?' . http_build_query($param);

        $res = self::curlGet($curl, $url);

        if($res && $res['retCode'] == 0)
        {
            return $res['data'];
        }

        return [];
    }

    private static function curlGet($curl, $url){
        $res = $curl->get($url, true);
        if($res === false){
            throw new \Exception('调用extapi(' . $url . ')出错:' . $curl->response);
        }
        return json_decode($res,true);
    }
}